package com.smt.take.ui.activity

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.smt.take.R
import com.smt.take.ui.fragment.HomeFragment
import com.smt.take.ui.fragment.MoreFragment
import com.smt.take.ui.fragment.OrderFragment
import com.smt.take.ui.fragment.UserFragment
import kotlinx.android.synthetic.main.activity_confirm_order.*
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : BaseActivity() {

    private val fragments: List<Fragment> = listOf(
        HomeFragment(), OrderFragment(),
        UserFragment(), MoreFragment()
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // 判断设备是否有虚拟按键
        if (checkDeviceHasNavigationBar(this)) {
            ll_main_activity.setPadding(0, 0, 0, 48.dp2px())
        }
        initBottomBar()
        changeIndex(0)
    }

    private fun initBottomBar() {
        for (i in 0 until main_bottom_bar.childCount) {
            main_bottom_bar.getChildAt(i).setOnClickListener {
                changeIndex(i)
            }
        }
    }

    private fun changeIndex(index: Int) {
        for (i in 0 until main_bottom_bar.childCount) {
            val child = main_bottom_bar.getChildAt(i)
            if (i == index) {
                // 选中，禁用效果
                setEnable(child, false)
            } else {
                // 没有选中，enable = true
                setEnable(child, true)
            }
        }
        // Androidx内使用getFragmentManager方法失效解决方法
        // 需要使用activity继承FragmentActivity并使用FragmentActivity内的方法
        // getSupportFragmentManager()
        supportFragmentManager.beginTransaction().replace(R.id.main_content, fragments[index])
            .commit()
    }

    private fun setEnable(child: View, isEnable: Boolean) {
        child.isEnabled = isEnable //更改孩子的状态
        if (child is ViewGroup) {
            for (i in 0 until child.childCount) {
                // 修改孙子的状态
                child.getChildAt(i).isEnabled = isEnable
            }
        }
    }

}